package whackTheMole;

import java.util.Iterator;

import mote.Mote;
import mote.MoteBridge;
import mote.MoteCollection;
import mote.MoteInterface;

public class Mole
{
	/*static final int DarkLevel = 10;*/
	static final int DARK_OFFSET = 5;
	
	public static void main(String arg[])
	{
		MoteCollection motes = new MoteCollection();
		MoteInterface bridge = new MoteBridge(motes);
		
		byte LEDsOn = 7;
		byte LEDsOff = 0;
		int curLevel = 1000;
		int Score = 0;
		int LightLevel = 0; //keeps the maximum LightLevel found during initilization
		int Missed = 0;
		
		int curReading;
		
		while(motes.Count() < 1)
		{
			
		}
		
		Iterator<Mote> it = motes.Motes().iterator();
		
		while(it.hasNext())
		{
			Mote cur = it.next();
			
			if(cur.Reading() > LightLevel)
			{
				LightLevel = cur.Reading();
			}
			
			bridge.setSamplingInterval(cur.GetId(), 2);
			bridge.setLEDs(cur.GetId(), LEDsOff);
		}
		
		while(true)
		{
			//select a random mote
			//Mote cur = motes.Motes().get((int)Math.floor(Math.random() * 10) % motes.Motes().size());
			
			
			Mote cur = motes.getNthMote((int)(Math.random()*motes.Count()));
			
			curReading = cur.Reading();
			
			bridge.setLEDs(cur.GetId(), LEDsOn);
			
			try
			{
				Thread.sleep(curLevel);
			}
			catch(Exception e)
			{
				
			}
			
			//System.out.println("Reading: "+cur.Reading()+" hit threshold "+)cur
			
			if(cur.Reading() < curReading - DARK_OFFSET)
			{
				Score += 1;
				
				System.out.println("You got one!");

				if(curLevel > 200)
				{
					curLevel -= 25; //increase the speed
				}
				else //you win
				{
					System.out.println("You won :) your score is " + Score + ", you have missed " + Missed);
					System.exit(0);
				}
			}
			else
			{
				Missed++;
				
				System.out.println("Too slow.");
				
				if(Missed >= 20)
				{
					System.out.println("You have missed " + Missed + " moles, Game Over!!");
					System.exit(0);
				}
			}
						
			bridge.setLEDs(cur.GetId(), LEDsOff);

			while(cur.Reading() < curReading - DARK_OFFSET) //wait for the hand to be removed
			{
				
			}
		}
	}	
}
